package com.camic.core.loader
{
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;

	/**
	 * 资源加载器 
	 * @author Norris
	 */	
	public class ResLoader
	{
		private var m_Loader:XLoader = null;
		
		private var m_fnLoaded:Function = null;
		private var m_fnLoadError:Function = null;
		
		public function ResLoader()
		{
			super();
			m_Loader = new XLoader();
		}
		
		/**
		 * 
		 * @param strUrl
		 * @param fnLoaded				fnLoaded(l:ResLoader):void
		 * @param fnLoadError				fnLoadError(l:ResLoader):void
		 * 
		 */		
		public function load(strUrl:String, fnLoaded:Function = null, fnLoadError:Function = null):void {
			m_fnLoaded = fnLoaded;
			m_fnLoadError = fnLoadError;
			
			addEvents();
			m_Loader.load(new URLRequest(strUrl));
		}
		
		public function isLoading():Boolean {
			return m_Loader.isLoading();
		}
		
		public function stop():void {
			removeEvents();
			m_Loader.close();
			m_fnLoaded = null;
			m_fnLoadError = null;
		}
		
		public function getLoader():Loader {
			return m_Loader;
		}
		
		public function getLoaderContent():DisplayObject {
			return m_Loader.content;
		}
		
		public function destroy():void {
			removeEvents();
			m_Loader.destroy();
			m_Loader = null;
			m_fnLoaded = null;
			m_fnLoadError = null;
		}
		
		private function __OnComplete(e:Event):void {
			removeEvents();
			
			if (m_fnLoaded != null) {
				m_fnLoaded(this);
			}
		}
		
		private function __OnIOError(e:IOErrorEvent):void {
			removeEvents();
			
			if (m_fnLoadError != null) {
				m_fnLoadError(this);
			}
		}
		
		private function addEvents():void {
			m_Loader.contentLoaderInfo.addEventListener(Event.COMPLETE, __OnComplete);
			m_Loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, __OnIOError);
		}
		private function removeEvents():void {
			m_Loader.contentLoaderInfo.removeEventListener(Event.COMPLETE, __OnComplete);
			m_Loader.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, __OnIOError);
		}
	}
}